package org.learn.sharding.jdbc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dangdang.ddframe.rdb.sharding.api.ShardingDataSourceFactory;
import com.dangdang.ddframe.rdb.sharding.api.rule.DataSourceRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.ShardingRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.TableRule;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.TableShardingStrategy;
import com.google.common.collect.Lists;

@Component
public class XbDataSource {

    @Autowired
    DataSource dataSource;

    DataSource shardingDataSource;

    @PostConstruct
    public void init() {
        HashMap<String, DataSource> map = new HashMap<>();
        map.put("dataSource", dataSource);
        DataSourceRule dataSourceRule = new DataSourceRule(map);

        List<TableRule> tableRuleList = new ArrayList<>();
        List<String> pList = new ArrayList<>();
        for (int i = 1; i < 14; i++) {
            pList.add("tb_p_" + i);
        }
        //tb_p逻辑表名，pList实际所有的分表
        tableRuleList.add(new TableRule.TableRuleBuilder("tb_p")
                .actualTables(pList)
                .dataSourceRule(dataSourceRule)
                .tableShardingStrategy(new TableShardingStrategy("item_id", new ProgramShardingAlgorithm())).build());
        tableRuleList.add(new TableRule.TableRuleBuilder("tb_item")
                .actualTables(Lists.newArrayList("tb_item"))
                .dataSourceRule(dataSourceRule).build());
        ShardingRule shardingRule = ShardingRule.builder()
                .dataSourceRule(dataSourceRule)
                .tableRules(tableRuleList)
                .build();
        shardingDataSource = ShardingDataSourceFactory.createDataSource(shardingRule);
    }

    public DataSource getDataSource() {
        return shardingDataSource;
    }
}